<template>
  <div>
    <nav-bar right-text="注册" />
    <!-- <van-nav-bar class="my-nav-bar" left-arrow right-text="注册" /> -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <span @click="isPass = !isPass"
        >{{ isPass ? ' 短信验证码登录' : '密码登录' }}<van-icon name="arrow"
      /></span>
    </div>
    <van-form @submit="onSubmit" ref="formRef">
      <van-cell>
        <van-field
          name="mobile"
          v-model="formData.mobile"
          placeholder="请输入手机号"
          :rules="[
            { required: true, message: '必须输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号不合法' }
          ]"
        />
      </van-cell>
      <van-cell>
        <template v-if="isPass">
          <van-field
            :type="show ? 'text' : 'password'"
            name="password"
            v-model="formData.password"
            placeholder="请输入密码"
            :rules="[
              { required: true, message: '密码不能为空' },
              { pattern: /^\w{6,16}$/, message: '密码必须是6-16位' }
            ]"
          >
            <template #button>
              <icon
                @click="show = !show"
                :name="`login-eye-${show ? 'on' : 'off'}`"
              />
            </template>
          </van-field>
        </template>
        <template v-else>
          <van-field
            type="text"
            name="code"
            v-model="formData.code"
            placeholder="请输入验证码"
            :rules="[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码必须是6位' }
            ]"
          >
            <template #button>
              <span
                class="btn-send"
                :class="{ active: time > 0 }"
                @click="getCode"
                >{{ time > 0 ? `${time}秒后重试` : '发送验证码' }}</span
              >
            </template>
          </van-field>
        </template>
      </van-cell>
      <div class="cp-cell">
        <van-checkbox v-model="checked">
          <span>我已同意</span><a href="">用户协议</a><span>及</span
          ><a href="">隐私条款</a></van-checkbox
        >
      </div>
      <div class="cp-cell">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
      <div class="cp-cell">忘记密码?</div>
    </van-form>
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <!-- <div class="icon" id="qq"></div> -->
      <div class="icon">
        <a
          :href="qqUrl"
          @click="login.setRedirectUrl($route.query.redirectUrl as string)"
        >
          <img src="@/assets/images/qq.svg" alt="" />
        </a>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, reactive, onUnmounted } from 'vue'
import { Toast } from 'vant'
import request from '@/utils/request'
import { ApiRes } from '@/types/data'
import { LoginRes } from '@/types/login'
import useStore from '@/store'
import { useIntervalFn } from '@vueuse/core'
import { FormInstance } from 'vant'
import { loginByQQ } from '@/api/user'
const { login } = useStore()
const route = useRoute()
const router = useRouter()
const show = ref(false)
// 是否是密码登录
const isPass = ref(true)
const formRef = ref(null)
const formData = reactive({
  password: 'abc12345',
  mobile: '13230000001',
  code: ''
})
// 是否同意
const checked = ref(true)

const time = ref(0)
const { pause, resume, isActive } = useIntervalFn(() => {
  console.log('---useIntervalFn---')
  /* your function */
  time.value--
  if (time.value <= 0) {
    pause()
  }
}, 1000)
pause()

// 获取验证码
const getCode = async () => {
  if (time.value > 0) return
  try {
    await (formRef.value! as FormInstance).validate(['mobile'])

    const res = await request.get(`code?type=login&mobile=${formData.mobile}`)
    if (res.data.code === 10000) {
      Toast({ type: 'text', message: res.data.data.code, duration: 2000 })

      // 开始倒计时
      time.value = 60
      resume()
    } else {
      time.value = 0
      Toast({ type: 'text', message: res.data.message, duration: 1000 })
    }
  } catch (error) {
    console.log(error)
  }
}
onUnmounted(() => {
  pause()
})

// 提交（密码或是验证码登录）
const onSubmit = async (values: any) => {
  if (!checked.value) {
    Toast('请勾选用户协议')
    return
  }
  let res = null
  if (isPass.value) {
    res = await request.post<ApiRes<LoginRes>>('login/password', values)
  } else {
    res = await request.post<ApiRes<LoginRes>>('login', values)
  }
  if (res.data.code === 10000) {
    // 提示
    Toast({ type: 'success', message: '登录成功', duration: 800 })
    // 把登录之后的登录信息保存到pinia和本地
    login.setLoginInfo(res.data.data)
    // 是否有来源页面
    if (route.query.redirectUrl) {
      router.replace(decodeURI(route.query.redirectUrl as string))
    } else {
      // 默认跳转到layout
      router.push('/')
    }
  } else {
    Toast.fail(res.data.message)
  }
}

// onMounted(() => {
//   // 组件渲染完毕，使用QC生成QQ登录按钮，目的得到跳转链接
//   QC.Login({
//     btnId: 'qq'
//   })
// })
const qqUrl = `https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=${encodeURIComponent(
  import.meta.env.VITE_CALLBACK + '/login/callback'
)}`
</script>

<style lang="scss" scoped>
.login {
  &-head {
    padding: 30px 30px 50px;
    margin-top: 46px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-icon {
    margin-right: 10px;
  }
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      border-color: var(--cp-primary);
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
  }
  .active {
    color: #16c2a380;
  }
}
</style>
